---
name: useLocalStorageState
route: /useLocalStorageState
menu: 'State'
edit: false
sidebar: true
---

import JackBox from 'jackbox';

import Demo1 from './demo/demo1';
import Demo1CodeTsx from '!raw-loader!./demo/demo1.tsx';
import Demo1CodeJsx from '!raw-loader!./demo/demo1.jsx';

import Demo2 from './demo/demo2';
import Demo2CodeTsx from '!raw-loader!./demo/demo2.tsx';
import Demo2CodeJsx from '!raw-loader!./demo/demo2.jsx';

import Demo3 from './demo/demo3';
import Demo3CodeTsx from '!raw-loader!./demo/demo3.tsx';
import Demo3CodeJsx from '!raw-loader!./demo/demo3.jsx';

# useLocalStorageState

A Hook for persisting state into localStorage.

## Examples

<JackBox jsCode={Demo1CodeJsx} tsCode={Demo1CodeTsx} demoName='Persist state into localStorage' description='Refresh this page and you will find the value of input box get restored from localStorage.'>
  <Demo1 />
</JackBox>

<JackBox jsCode={Demo2CodeJsx} tsCode={Demo2CodeTsx} demoName='Persist objects' description='useLocalStorageState will do the serialization and deserialization work automatically.'>
  <Demo2 />
</JackBox>

<JackBox jsCode={Demo3CodeJsx} tsCode={Demo3CodeTsx} demoName='Persist objects with function updater' description='function updater is also acceptable with useLocalStorageState.'>
  <Demo3 />
</JackBox>

## API

```typescript
const [state, setState] = useLocalStorageState<T>(
  key: string,
  defaultValue?: T | (() => T),
): [T?, (value?: T | ((previousState: T) => T)) => void]
```

The API is very similiar to `useState`, but there is an extra `key` parameter for specifying the key of localStorage. The return value is the same as `useState`. When `setState` gets called, it will update the new value to localStorage automatically.

If you want to delete this record from localStorage, you can use `setState()` or `setState(undefined)`.
